<template>
	<view class="item">
		<view class="i-head">
			<view class="shop">
				<uni-icons type="shop"></uni-icons>
				<view class="name" @click="handleShop(item.member_id)">
					{{item.shopname}}
				</view>
			</view>
			<view class="state">
				{{
				          item.status==3?(item.is_ready_check==1?'审核中':item.is_ready_check==2?'预审通过':item.is_ready_check==3?'匹配商家':'待审核'):
				          item.order_status_name}}
			</view>
		</view>
		<view class="i-center" @click="handleClickItem">
			<view class="goods-img">
				<image class="img" :src="getImg(item.imgurl)" mode="widthFix"></image>
			</view>
			<view class="goods-info">
				<view class="title">
					{{item.goods_title}}
				</view>
				<view class="set-meal">
					套餐：{{item.setmeal_title}}
				</view>
				<view class="time">
					租期：{{item.lease_time}}
				</view>
				<view class="all-price">
					总租期：{{item.rent_total}}（分{{item.month_total}}期）
					<view class="num">x{{item.amount}}</view>
				</view>
			</view>
		</view>
		<view class="i-foot">
			<view class="more" v-if="btns(item.status).length > 3" @click="handleMore">
				更多
				<view class="contact" v-show="showMore" @click.stop="handleService">联系客服</view>
			</view>

			<view class="btn" v-for="(ele,index) in btns(item.status)" :key="index"
				:class="[ele.class,index > 2 ? 'hide' : '',showMore ? 'show' : '']" @click="handleBtn(ele.name)">
				<!-- 
					第一个class判断有没有再次下单
					第二个class判断是不是大于2就隐藏后面到元素
					第三个用户点击之后显示被隐藏的是按钮
				-->
				{{ele.name}}
			</view>
		</view>
		<!-- 普通弹窗 -->
		<uni-popup ref="popup" background-color="#fff">
			<view class="popup-content" :class="{ 'popup-height': type === 'left' || type === 'right' }">
				<uni-section title="请选择支付方式" type="line">
					<uni-data-select :localdata="uniCode" @change="change"></uni-data-select>
				</uni-section>
			</view>
		</uni-popup>
		<!-- 普通弹窗 -->
		<uni-popup ref="popup1" background-color="#fff">
			<view class="popup-content1" :class="{ 'popup-height': type1 === 'left' || type1 === 'right' }">
				<uni-section title="请选择支付银行卡" type="line">
					<uni-data-select :localdata="uniCode1" @change="change1"></uni-data-select>
				</uni-section>
				<uni-section title="请输入验证码" type="line">
					<input type="text" placeholder="请输入验证码" :value="payCode"
						style="border: solid 1px #e5e5e5;height: 65rpx;width: 400rpx;">
					<button class="code_btn" :disabled="isSend1" @click="handleCode">{{codeName}}</button>
				</uni-section>
				<view class="" style="margin-top: -25rpx;">
					<button type="default" @click="goPay1">确认支付</button>
				</view>
			</view>
		</uni-popup>
		<!-- 申请归还弹窗 -->
		<uni-popup ref="returnBack" background-color="#fff" type="dialog">
			<view :class="{ 'popup-height': returnType === 'left' || returnType === 'right' }">
				<uni-popup-dialog :type="msgType" cancelText="取消" confirmText="确认归还"
					:title="this.item.status==40 || this.item.status==42 ? '订单到期！' :'订单未到期！'"
					content="是否确认归还商品？\n请在到期3天内归还，以免对您的押金退还造成影响。" @confirm="dialogApply" @close="dialogClose"></uni-popup-dialog>
			</view>
		</uni-popup>
		<uni-popup ref="returnBack1" background-color="#fff" type="dialog">
			<view :class="{ 'popup-height': returnType === 'left' || returnType === 'right' }">
				<uni-popup-dialog :type="msgType" cancelText="取消申请" confirmText="确认申请"
					:title="this.item.status==40 || this.item.status==42 ? '订单到期！' :'订单未到期！'"
					content="该商品允许提前归还，是否确认申请提前归还？\n归还后已缴付的租金不再退还，如有疑问请联系商家。" @confirm="dialogApply"
					@close="dialogClose"></uni-popup-dialog>
			</view>
		</uni-popup>
		<!-- 添加物流弹窗 -->
		<uni-popup ref="addLogistics" background-color="#fff" type="dialog">
			<view style="width:650rpx ;" :class="{ 'popup-height': type1 === 'left' || type1 === 'right' }">
				<uni-section title="请选择物流名称" type="line">
					<uni-data-select :localdata="flowList" @change="changeFlow"></uni-data-select>
				</uni-section>
				<uni-section title="请输入物流单号" type="line">
					<input type="text" placeholder="请输入物流单号" :value="flowNumber" @input="handleFlow"
						style="border: solid 1px #e5e5e5;height: 65rpx;">
				</uni-section>
				<view class="" style="margin-top: 20rpx;">
					<button type="default" @click="toFlow">确认添加</button>
				</view>
			</view>
		</uni-popup>
		<!-- 申请续租 -->
		<uni-popup ref="applyLease" background-color="#fff" type="dialog">
			<view :class="{ 'popup-height': returnType === 'left' || returnType === 'right' }">
				<uni-popup-dialog :type="msgType" cancelText="返回" confirmText="下一步"
					title="申请续租"
					:content="!goodsStatus ? '该商品已下架，暂无法续租！请联系商家' : '续租成功后，商品不再发货'" @confirm="dialogNext" @close="dialogClose"></uni-popup-dialog>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import orderState from "@/common/my-goods-order/orderState.js";
	import {
		readyPay,
		confirmPay,
		createContract,
		wechatPay,
		orderApplyReturn,
		getReturnExpressList,
		orderReturnCancel,
		orderReturnAddExpress,
		cancelOrderRefund
	} from '@/api/order'
	import redState from "@/common/my-goods-order/redState.js";
	// import { orderInfo, getOrderReturnAddress, orderReturnAddExpress, , , orderReturnCancel, orderPreAuth, getRenewalGoodsStatus,orderRecharge } from "../../../api/order";
	import {
		debounce
	} from '@/utils/debounce'
	export default {
		name: "card",
		props: ['item', 'list'],
		data() {
			return {
				showMore: false,
				type: '',
				type1: 'center',
				returnType: 'center',
				returnTitle: '申请归还',
				uniCode: [{
						value: 1,
						text: '微信支付'
					},
					{
						value: 2,
						text: '银行卡支付'
					}
				],
				flowId: '',
				accountId: '',
				codeName: '获取验证码',
				totalTime1: 60,
				isSend1: false, //禁用
				timer: '', //定时器
				payCode: '',
				uniCode1: '',
				unique_code2: '',
				flowList: [],
				flowNumber: '',
				flowName: '',
				flowIndex: '',
				type1:''
			}
		},
		created() {
			const list = uni.getStorageSync("uniqueCode");
			this.uniCode1 = list

		},
		methods: {
			handleClickItem() {
				uni.navigateTo({
					url: `/pagesA/my/order/myorder/orderDetail?order_id=${this.item.id}`,
				})
			},
			handleShop(member_id) {
				uni.navigateTo({
					url: `/pagesB/shopmall/mallIndex?member_id=${member_id}`
				})
			},
			handleBtn(name) {
				switch (name) {
					case "联系客服":
						this.handleService();
						break;
					case "再次下单":
						this.rewriteOrder();
						break;
					case "取消订单":
						this.cancelOrder();
						break;
					case "立即付款":
						this.payOrder();
						break;
					case "签署合同":
						this.goSign();
						break;
					case "申请退款":
						this.toApply();
						break;
					case "支付租金":
						this.toPay();
						break;
					case "申请归还":
						this.returnBack();
						break;
					case "取消归还":
						break;
					case "取消退款":
						this.canlePay();
						break;
					case "申请续租":
						this.applyLease();
						break;
					case "协议公证":
						this.notarization();
						break;
					case "继续提交":
						this.continueSubmit();
						break;
					case "上传证件":
						this.cardSubmit();
						break;
				}
			},
			// 上传身份证照片
			cardSubmit(){
					uni.navigateTo({
						url: '/pagesB/userCard/userCard'
					})
			},
			// 继续提交
			continueSubmit(){
				uni.navigateTo({
					url: `/pagesB/authentication/authentication?goodsId=${ this.item.goods_id }&orderId=${ this.item.id }`
				})
			},
			// 协议公证
			notarization(){
				uni.navigateTo({
					url: '/pagesB/notarization/notarization?orderId='+this.item.id
				})
			},
			// 申请续租
			applyLease(){
				this.$refs.applyLease.open(this.returnType)
			},
			// 取消退款
			canlePay(){
				cancelOrderRefund(this.item.id).then(res=>{
					 uni.showToast({
						icon: 'success',
						title: '操作成功',
					});
				})
			},
			// 取消归还
			canleBack: debounce(function() {
				orderReturnCancel(this.item.id).then(res => {
					uni.showToast({
						title: '撤销成功',
						icon: 'success'
					})
				})
			}, 500),
			handleFlow(e) {
				let reg = /^[0-9A-Za-z]+$/
				if (!reg.test(e.detail.value)) {
					my.showToast({
						icon: 'error',
						title: '请填写正确的物流单号',
					});
				}
				this.flowNumber = e.detail.value
			},
			changeFlow(e) {
				this.flowIndex = e
				this.flowName = e
			},
			toFlow() {
				let reg = /^[0-9A-Za-z]+$/
				if (this.flowIndex<-1) {
					uni.showToast({
						title: '请选择物流名称',
						icon: 'error'
					})
					return false
				}
				if (!this.flowNumber && this.flowIndex == '') {
					my.showToast({
						icon: 'error',
						title: '请填写物流单号',
					});
					return false
				}
				if (this.flowNumber && !reg.test(this.flowNumber)) {
					my.showToast({
						icon: 'error',
						title: '请填写正确的物流单号',
					});
					return false
				}
				orderReturnAddExpress({
					order_id:this.item.id,
					logistics_name: this.flowList[this.flowName].text,
					logistics_no: this.flowNumber,
				}).then(res=>{
					this.$refs.addLogistics.close()
					// 刷新当前页面
				})
			},
			// 申请归还
			returnBack() {
				if (this.item.status == 40 || this.item.status == 42) {
					this.$refs.returnBack.open(this.returnType)
				} else {
					this.$refs.returnBack1.open(this.returnType)
				}

			},
			dialogClose() {},
			dialogApply() {
				if(this.item.status == 40){
				getReturnExpressList().then(res => {
					this.$refs.returnBack.close()
					this.$refs.addLogistics.open(this.returnType)
					for (let i = 0; i < res.length; i++) {
						this.flowList.push({
							value: i,
							text: res[i].name
						})
					}
				})
				} else if( this.item.status==30|| this.item.status==39 ){
					orderApplyReturn(this.item.id).then(res =>{
						// 需要添加一个刷新列表操作
						this.$refs.returnBack1.close()
					})
				}
			},
			toPay() {
				console.log(this.item.id, 'orderId');
				uni.navigateTo({
					url: '/pagesA/my/order/myorder/payRent?order_id=' + this.item.id + '&isView=true'
				})
			},
			goSign: debounce(function(e) {
				uni.showLoading({
					title: "Loading",
					mask: true,
				})
				let data = {
					order_id: this.item.id
				}
				createContract(data).then(res => {
					if (res.type == '1') {
						uni.hideLoading();
						uni.showModal({
							title: res.msg,
							content: '绑定银行卡',
							success: function(res) {
								if (res.confirm) {
									uni.navigateTo({
										url: '/pagesB/addBank/addBank'
									})
								} else if (res.cancel) {
									uni.showToast({
										title: '请先完成绑卡',
										icon: 'error'
									})
								}
							}
						})
					} else {
						uni.hideLoading();
						this.flowId = res.flowId
						this.accountId = res.signerId
						uni.navigateToMiniProgram({
							appId: 'wx1cf2708c2de46337', // 公证签小程序APPID
							path: '/pages/index/index', // webview页面地址
							extraData: {
								// 入参
								requestObj: {
									flowId: res.flowId, // 签署/实名流程id
									accountId: this.accountId, // 账号id（仅签署需要）
									type: 'SIGN', // 业务类型：签署 SIGN（默认）, 实名 REALNAME
									env: 'prod', // 对接环境：线上 prod(默认）, 模拟 sml(用于对接调试阶段）
								},
								// 回传数据：签署/实名完成后会将此数据完整回传
								callbackObj: {
									test: '12345',
									'from': 'SIGN'
								},
							},
							success(res) {
								// 根据客户自身需要
							},
							fail(res) {
								// 根据客户自身需要
							},
							complete(res) {
								// 根据客户自身需要
							},
						})
					}
				})
			}, 2000),
			temp() {

			},
			goPay1() {
				if (this.payCode == '') {
					uni.showToast({
						title: "请先输入验证码",
						icon: 'error'
					})
					return
				}
				let data1 = {
					leaseId: this.selected,
					orderId: this.order,
					unique_code3: this.unique_code3,
					code: this.payCode
				}
				confirmPay(data1).then(res => {
					if (res.status == 200) {
						uni.showToast({
							title: "支付成功",
							icon: 'success'
						})
						this.$refs.popup.close()
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'error'
						})
						this.$refs.popup.close()
					}
				})
			},
			change1(e) {
				this.unique_code2 = e
			},
			change(e) {
				if (e == 1) {
					// 请求接口拿回数据---------微信支付
					let data = {
						orderId: this.item.id,
						total_fee: this.item.rent * 100,
						leaseId: ['1']
					}
					wechatPay(data).then(res => {
						let appId = res.appid
						let timeStamp = res.timeStamp + ''
						let nonceStr = res.nonce_str
						let packageX = res.prepay_id
						let signType = 'MD5'
						let paySign = res.paySign
						uni.requestPayment({
							"provider": "wxpay",
							appId: appId,
							prepay_id: packageX,
							nonceStr: nonceStr,
							package: 'prepay_id=' + packageX,
							timeStamp: timeStamp,
							paySign: paySign,
							signType: 'MD5',
							success(res) {
								console.log('success', res);
							},
							fail(e) {
								console.log('fail', e);
							}
						})
					})
				} else {
					this.$refs.popup.close()
					this.$refs.popup1.open(this.type1)
				}
			},
			nowPay() {

			},
			toApply: debounce(function(e) {
				uni.navigateTo({
					url: '/pagesB/applyRefund/applyRefund?order_id=' + this.item.id
				})
			}, 100),
			payOrder() {
				this.type = 'center'
				this.$refs.popup.open(this.type)
			},
			cancelOrder() {
				uni.showLoading({
					title: "Loading",
					mask: true,
				})
				uni.$http.post('/Wechat/Order/orderCancel', {
					order_id: this.item.id
				}).then(res => {
					if (res.data.status === 200) {
						uni.hideLoading();
						uni.$emit("deleteItem", this.item.id);
						uni.showToast({
							title: res.data.msg,
							icon: "none",
						})
					} else {
						uni.showToast({
							title: res.data.msg,
							icon: "error",
						})
					}
				}).finally(() => {
					uni.hideLoading();

				})
			},
			rewriteOrder() {
				uni.navigateTo({
					url: `/pagesA/category/goods/productDetails/productDetails?id=${this.item.goods_id }`
				})
			},
			handleService() {
				uni.switchTab({
					url: "/pages/service/service",
				})
			},
			handleMore() {
				this.showMore = !this.showMore;
			},
			btns(status) {
				let data = [];
				orderState.forEach(item => {
					// 屏蔽我的订单页面显示
					if(item.name=='确定'||item.name=='去提交'){
						
					}else{
						const bool = item.status.includes(status);
						if (bool) {
							if (redState.includes(item.name)) {
								item.class = 'red';
							}
							data.unshift(item);
						}
						if(item.name=='协议公证'&&this.item.is_lease==2){
							data.shift(item);
						}
					}
				})
				
				return data;
			},
			handleCode() {
				let data = {
					unique_code2: this.unique_code2,
					txn_amt: this.total * 100,
					orderId: this.order
				}
				if (this.unique_code2 == '') {
					uni.showToast({
						title: "请先选择银行卡",
						icon: 'error'
					})
					return
				}
				readyPay(data).then(res => {
					this.unique_code3 = res[0]
					this.makePrice = res[1]
				})
				this.isSend1 = true
				this.codeName = this.totalTime1 + 's后重新发送'
				this.timer1 = setInterval(() => {
					this.totalTime1--
					this.codeName = this.totalTime1 + 's后重新发送'
					if (this.totalTime1 < 0) {
						clearInterval(this.timer1)
						this.codeName = '重新发送验证码'
						this.totalTime1 = 60
						this.isSend1 = false
					}
				}, 1000)
			},
			getImg(src) {
				return getApp().globalData.baseImg + src;
			},
		}
	}
</script>

<style lang="scss" scoped>
	.popup-content {
		width: 600rpx;
		height: 200rpx;
	}

	.popup-content1 {
		width: 700rpx;
		height: 450rpx;
	}

	.code_btn {
		position: relative;
		left: 200rpx;
		bottom: 70rpx;
		height: 70rpx;
		width: 250rpx;
		font-size: 30rpx;
	}

	.item {
		background-color: white;
		border-radius: 10rpx;
		margin-bottom: 20rpx;

		.i-head {
			padding: 20rpx;
			font-size: 28rpx;
			display: flex;
			justify-content: space-between;

			.shop {
				.name {
					margin-left: 20rpx;
					display: inline-block;
				}
			}

			.state {
				color: #e8ad5c;
				font-size: 26rpx;
			}
		}

		.i-center {
			padding: 30rpx 20rpx;
			display: flex;
			position: relative;
			border-top: 1rpx solid #ececec;
			border-bottom: 1rpx solid #ececec;

			.goods-img {
				width: 200rpx;
				height: 200rpx;

				.img {
					width: 200rpx;
				}
			}

			.goods-info {
				display: flex;
				flex-direction: column;
				margin-left: 20rpx;

				.title {
					font-size: 30rpx;
				}

				.set-meal,
				.time {
					color: #a8a8a8;
					font-size: 28rpx;
				}

				.all-price {
					font-size: 30rpx;
					position: absolute;
					bottom: 20rpx;
					display: flex;
					align-items: center;

					.num {
						color: #a8a8a8;
						font-size: 26rpx;
						margin-left: 20rpx;
					}
				}
			}
		}

		.i-foot {
			padding: 20rpx;
			display: flex;
			align-items: center;
			justify-content: flex-end;
			position: relative;
			flex-wrap: wrap;
			padding-top: 10rpx;

			.more {
				position: absolute;
				left: 25rpx;
				font-size: 28rpx;
				color: #bbbbbb;
				top: 50%;
				transform: translateY(-50%);

				.contact {
					position: absolute;
					padding: 10rpx 20rpx;
					background-color: #333333;
					transform: translateY(-200%);
					white-space: nowrap;
					border-radius: 5rpx;
					font-size: 24rpx;

					&::before {
						content: " ";
						display: inline-block;
						border: 6rpx solid transparent;
						border-top-color: #333333;
						position: absolute;
						left: 10rpx;
						bottom: 0;
						transform: translateY(100%);
					}
				}
			}

			.btn {
				// width: 120rpx;
				height: 35rpx;
				padding: 10rpx 20rpx;
				border-radius: 30rpx;
				text-align: center;
				margin-left: 10rpx;
				font-size: 24rpx;
				color: #bbbbbb;
				border: 2rpx solid #bbbbbb;
				margin-top: 10rpx;

				&.red {
					color: #fff;
					border: 2rpx solid #ff0000;
					background-color: #ff0000;
				}

				&.hide {
					display: none;
				}

				&.show {
					display: inline-block;
				}
			}
		}
	}
</style>